package com.sdjzu.wangfuying.androidusbserialportlib.util;
/*
作者：王福迎
邮箱：<805447391@qq.com>
网址：https://gitee.com/wangfuying_admin
*/

import android.app.PendingIntent;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.OnLifecycleEvent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;

import java.util.ArrayList;
import java.util.List;

public class UsbSerialPortUtil {

    private static final String ACTION_USB_PERMISSION = "com.sdjzu.wangfuying.androidusbserialport.USB_PERMISSION";

    /**
     * 列举所有连接到设备上的串口
     *
     * @param context
     * @param listener
     */
    public static void listSerialPort(final Context context, final OnListedSerialPortListener listener) {
        new AsyncTask<Void, Void, List<UsbSerialPort>>() {
            @Override
            protected List<UsbSerialPort> doInBackground(Void... params) {
                UsbManager mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
                final List<UsbSerialDriver> drivers =
                        UsbSerialProber.getDefaultProber().findAllDrivers(mUsbManager);

                final List<UsbSerialPort> result = new ArrayList<UsbSerialPort>();
                for (final UsbSerialDriver driver : drivers) {
                    final List<UsbSerialPort> ports = driver.getPorts();
                    result.addAll(ports);
                }
                return result;
            }

            @Override
            protected void onPostExecute(List<UsbSerialPort> result) {
                listener.onFinished(result);
            }

        }.execute((Void) null);
    }

    public static Connection connect(final Context context, final UsbSerialPort usbSerialPort, final OnConnectedCallback callback) {
        final UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        assert usbManager != null;
        final Connection connection = new Connection(context, usbSerialPort);
        if (usbManager.hasPermission(usbSerialPort.getDriver().getDevice())) {
            callback.onConnected(connection);
        } else {
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (ACTION_USB_PERMISSION.equals(action)) {
                        synchronized (this) {
                            if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                                callback.onConnected(connection);
                            } else {
                                callback.onGrantFailed(context, usbSerialPort);
                            }
                        }
                    } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                        connection.getListener().onError(connection, new Exception(UsbManager.ACTION_USB_DEVICE_DETACHED));
                        connection.close();
                    } else {
                        Log.d("mUsbReceiver", "action");
                    }
                }
            };
            context.registerReceiver(mUsbReceiver, filter);
            if (context instanceof FragmentActivity) {
                ((FragmentActivity) context).getLifecycle().addObserver(new LifecycleObserver() {
                    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                    void onDestroy(LifecycleOwner activity) {
                        context.unregisterReceiver(mUsbReceiver);
                    }
                });
            }
            usbManager.requestPermission(usbSerialPort.getDriver().getDevice(), PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0));
        }
        return connection;
    }

}
